import Plugin from './plugin'
import {CN,EN,Web} from '../config'

const cssText = `
.#{icn.text} {
	position:absolute; 
	outline: none;
    border: none;
    text-indent: 0;
    line-height: 20px;
    font-size: 14px;
    min-width: 70px;
    height: 20px;
    background-color: #fff;
    box-sizing: border-box;
}
.#{icn.text}:focus {
    border-bottom: 1px solid #{icn.theme}
}
`
const tpl = `<div class="${CN.abs}">
			<input autofocus="autofocus"/>
		</div>`
export default class TextPicker extends Plugin{
	constructor(...args){
		super(...args)
		this.name="TextPicker"
		this.createClassName({
			text:"text-input"
		})
		this.injectStyle(cssText,this.cn)
		this.render()
		this.bind()
	}
	render(){
		this.span = document.createDOM("span")

		this.$dom = document.createDOM("div",{
			class:`${CN.hide} ${CN.layer}`
		})
		this.$dom.innerHTML = tpl
		this.$picker = this.$dom.query("."+CN.abs)
		this.input = this.$picker.children[0]
		this.input.className = this.cn.text
		this.$event.emit(EN.layout_render,this.$dom)
	}
	bind(){
		this.$picker.addEventListener("click",(e)=>{
			e.stopPropagation();
		})

		this.input
		.addEventListener("change",this.onPick.bind(this))

		this.$dom.addEventListener("click",()=>{
			this.focusOut()
		})
	}
	onPick(e){
		let text = this.input.value;
		this.span.innerHTML = text;
		let res={
			text,
			html:this.span.innerText
		}
		this.focusOut(res);
	}
	focusOut(text){
		this.$event.emit(EN.input_done,text)
		this.input.value="";
		this.$dom.classList.add(CN.hide);
	}
	focusIn(data){
		let {x,y,text,w,placeholder,strokeStyle,scale} = data
		this.input.setAttribute("placeholder",placeholder)
		setTimeout(()=>{
			this.input.focus()
			text&&this.input.select()
		},50)
		if(text)
			this.input.value = text
		if(w)
			this.input.style.width = w+"px"
		if(strokeStyle)
			this.input.style.color = strokeStyle
		this.$picker.style.cssText=`
		left:${x}px;
		top:${y-Web.cvsLineHeight*scale/2}px;
		transform-origin:left center;
		transform:translate3d(0,0,0) scale(${scale});
		`
		this.$dom.classList.remove(CN.hide);
	}
}